/** 
* Copyright 2010 Cristian Costantini - Millemultimedia.it
* License: http://www.apache.org/licenses/LICENSE-2.0
* @author      Cristian Costantini | cristian@millemultimedia.it
* Version: 1.0.0 alpha 3
*/
Ext.namespace('fileManager.plugin.PluginManager.handler');

fileManager.plugin.PluginManager.handler.manage = function(){
	
	var fields = [
		'name',
		'version',
		'provider'
	];
	
    var firstGridStore = new Ext.data.JsonStore({
        url : services.pluginmanager.getPluginList,
		root   : 'installed',
		fields:fields,
		storeId:'firstGridStore'
    });

	var cols = [
		{ id: 'name', header: "Plugin Name", width: 70, sortable: true, dataIndex: 'name'},
		{header: "Version", width: 50, sortable: false, dataIndex: 'version'},
		{header: "Provider", width: 150, sortable: false, dataIndex: 'provider'}
	];

    this.firstGrid = new Ext.grid.GridPanel({
		ddGroup          : 'secondGridDDGroup',
        store            : firstGridStore,
        columns          : cols,
		enableDragDrop   : true,
        stripeRows       : true,
        autoExpandColumn : 'name',
        title            : 'Installed Plug-in'
		
    });
	
	this.firstGrid.store.load();

    var secondGridStore = new Ext.data.JsonStore({
        url : services.pluginmanager.getPluginList,
		root   : 'uninstalled',
		fields:fields,
		storeId:'secondGridStore'
    });
	

    this.secondGrid = new Ext.grid.GridPanel({
		ddGroup          : 'firstGridDDGroup',
        store            : secondGridStore,
        columns          : cols,
		enableDragDrop   : true,
        stripeRows       : true,
        autoExpandColumn : 'name',
        title            : 'Uninstalled Plug-in'
    });

	this.secondGrid.store.load();
	
	var	bookTplMarkup = [
			'<div id="garbage" style="float:left;"><img src="/fileManager/plugin/pluginmanager/assets/ico/Garbage.png" height="40" width="40" style="margin:20px 30px;" /></div>',
			'<div id="reload"  style="float:left;" ><img onclick="location.href = currentFullPath + \'?reload=true\'" src="/fileManager/plugin/pluginmanager/assets/ico/Reload.png" height="40" width="40" style="margin:20px 30px;" /></div>'
			];
			
	var bookTpl = new Ext.Template(bookTplMarkup);
	
	
	var displayPanel = new Ext.Panel({
		width        : 650,
		height       : 300,
		layout       : 'hbox',
		defaults     : { flex : 1 }, //auto stretch
		layoutConfig : { align : 'stretch' },
		items        : [
			this.firstGrid,
			this.secondGrid
		]
	});
	
	
	var blankRecord =  Ext.data.Record.create(fields);

    this.window = new Ext.Window({
        width: 650,
        height: 415,
		draggable: false,
        title: 'Plug-in manager',
		items:[
			displayPanel,
			bookTpl
			]
		});
		
	
		
	this.window.show(this);
		
	var firstGridDropTargetEl =  this.firstGrid.getView().scroller.dom;
    var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
            ddGroup    : 'firstGridDDGroup',
            notifyDrop : function(ddSource, e, data){
                    var records =  ddSource.dragData.selections;
                    Ext.each(records, ddSource.grid.store.remove, ddSource.grid.store);
                    firstGridStore.add(records);
                    firstGridStore.sort('name', 'ASC');
					Ext.Ajax.request({
							url: services.pluginmanager.changeStatus,
							method: 'post',
							params: {
								name: data.selections[0].data.name,
								status:true
							},
							sync: true,
							success: function(response, options){
								var res = Ext.util.JSON.decode(response.responseText);
								var log1 = document.getElementById("logArea").value;
								if (res.success == true) {
									document.getElementById("logArea").value = getCurrentTime() + ' | Plugin ' + options.params.name + ' installed\n' + log1;
									new Ext.ToolTip({
										target: reload,
										title: 'Reload to apply changes',
										maxWidth: 120
									});
									new Ext.ux.ToastWindow({
									    title: 'Plugin manager',
									    html: '<p style="padding:5px;">One or more plugins was installed, reload to apply changes</p>',
									    iconCls: 'error'
									}).show(document);
								}
								else {
									Ext.Msg.alert( res.message );
									document.getElementById("logArea").value = getCurrentTime() + ' | ' + res.message + '\n' + log1;
								}
							}
						});
                    return true
            }
    });


    var secondGridDropTargetEl = this.secondGrid.getView().scroller.dom;
    var secondGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
            ddGroup    : 'secondGridDDGroup',
            notifyDrop : function(ddSource, e, data){
                    var records =  ddSource.dragData.selections;
                    Ext.each(records, ddSource.grid.store.remove, ddSource.grid.store);
                    secondGridStore.add(records);
                    secondGridStore.sort('name', 'ASC');
					Ext.Ajax.request({
							url: services.pluginmanager.changeStatus,
							method: 'post',
							params: {
								name: data.selections[0].data.name,
								status:false
							},
							sync: true,
							success: function(response, options){
								var res = Ext.util.JSON.decode(response.responseText);
								var log1 = document.getElementById("logArea").value;
								if (res.success == true) {
									document.getElementById("logArea").value = getCurrentTime() + ' | Plugin ' + options.params.name + ' uninstalled\n' + log1;
									new Ext.ToolTip({
										target: reload,
										title: 'Reload to apply changes',
										maxWidth: 120
									});
									new Ext.ux.ToastWindow({
									    title: 'Plugin manager',
									    html: '<p style="padding:5px;">One or more plugins was installed, reload to apply changes</p>',
									    iconCls: 'error'
									}).show(document); 
								}
								else {
									Ext.Msg.alert( res.message );
									document.getElementById("logArea").value = getCurrentTime() + ' | ' + res.message + '\n' + log1;
								}
							}
						});
                    return true
            }
    });
	
	var garbageDropTargetEl =  document.getElementById('garbage');
	
	var reload =  document.getElementById('reload');
	
	var garbageDrop = new Ext.dd.DropTarget( garbageDropTargetEl,{ddGroup:'firstGridDDGroup'});
	garbageDrop.notifyDrop = function(dd, e, data){
			Ext.Ajax.request({
							url: services.pluginmanager.uninstallPlugin,
							method: 'post',
							params: {
								name: data.selections[0].data.name
							},
							sync: true,
							success: function(response, options){
								var res = Ext.util.JSON.decode(response.responseText);
								var log1 = document.getElementById("logArea").value;
								if (res.success == true) {
									secondGridStore.load({});
									Ext.Msg.alert( 'Plugin ' + data.selections[0].data.name + ' are been deleted.' );
								}
								else {
									Ext.Msg.alert( res.message );
								}
							}
						});
					
                    return true
	};

	
};

fileManager.plugin.PluginManager.handler.install = function(dd, e, data){
		Ext.Msg.show({
			title: 'Install file ' + data.selections[0].data.name + ' to plugin register',
			msg: 'Are you sure?',
			width: 300,
			height: 200,
			buttons: {
				yes: true,
				no: true,
				cancel: false
			},
			fn: function(btn){
				switch (btn) {
					case 'yes':
					
						Ext.Ajax.request({
							url: services.pluginmanager.installPlugin,
							method: 'post',
							params: {
								source: "/" + data.selections[0].data.relativepath
							},
							sync:true,
							success:function( response, options ){
								var res = Ext.util.JSON.decode(response.responseText);
								if( res.success == true ){
									
									new fileManager.plugin.PluginManager.handler.manage();
									
								}else{
									
								}
							}
						});

						break;
					case 'no':
						
						break;
				}
			}
		});
return true;
}

